package com.itheima.web.servlet;

import cn.hutool.core.io.IoUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.BeanFactory;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import com.itheima.service.impl.StudentServiceImpl;
import com.itheima.service.impl.StudentServiceImpl2;
import com.itheima.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/api/student")
public class StudentServlet extends BaseServlet {

    public StudentServlet(){
        super();
    }

    //有耦合问题：private StudentService studentService = new StudentServiceImpl();

    private StudentService studentService = (StudentService) BeanFactory.getBean("studentService");


    /**
     * 分页查询学生信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void findPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //定义默认值
        int pageNum = 1;
        int pageSize = 5;
        //接收请求参数，并给pageNum和pageSize分别赋值
        try{
            pageNum = Integer.parseInt(request.getParameter("pageNum"));
        }catch (Exception e){
            System.out.println("没有传入pageNum，查询第一页");
        }
        //接收请求参数，并给pageNum和pageSize分别赋值
        try{
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }catch (Exception e){
            System.out.println("没有传入pageSize，查询"+pageSize+"条数据");
        }



        //1.调用service分页查询学生信息
        PageInfo pageInfo = studentService.findPage(pageNum, pageSize);
        //2.把查询结果转成json
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(pageInfo);
        //3.把json写回到浏览器端
        response.getWriter().write(json);
    }

    /**
     * 查询所有
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.调用service查询
        List<Student> students = studentService.findAll();
        //2.把students转成json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(students);
        //3.使用字符输出流，把json写到浏览器端
        response.getWriter().write(json);
    }

    /**
     *  json格式数据的体现形式是:
     *      {key:value,key:value}
     *  request对象获取请求参数的方法：
     *      String value = req.getParameter(name);
     *      请求参数的体现形式要求：
     *              key=value&key=value
     *              例如： method=delete&id=1
     *  注意：
     *      当浏览器请求过来的数据是json格式时，我们无法使用getParameter系列的方法获取请求参数。
     *      此时的解决办法：
     *             用流来获取。
     *             request.getInputStream();
     * 保存
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            //1.获取请求参数的字节输入流
            InputStream in = request.getInputStream();
            //2.把字节输入流转成json字符串
            String json = IoUtil.read(in, "UTF-8");
            System.out.println(json);
            //3.把Json的字符串转成Student对象
            ObjectMapper objectMapper = new ObjectMapper();
            Student student = objectMapper.readValue(json, Student.class);
            System.out.println(student);
            //4.调用service完成保存
            studentService.save(student);
            //5.回写ok
            response.getWriter().write("ok");
        }catch (Exception e){
            response.getWriter().write("error");
        }
    }

    /**
     * 根据id查询
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求参数中的id。
        String id = request.getParameter("id");
        //2.使用id，调用业务层查询学生信息
        Student student = studentService.findById(id);
        //3.把student对象转换成json
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(student);
        //4.把json写到浏览器端
        response.getWriter().write(json);
    }

    /**
     * 更新
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            //1.获取请求的字节输入流
            InputStream in = request.getInputStream();
            //2.使用IoUtil把字节输入流转成json字符串
            String json = IoUtil.read(in,"UTF-8");
            //3.把json字符串转成student对象
            ObjectMapper objectMapper = new ObjectMapper();
            Student student = objectMapper.readValue(json, Student.class);
            //4.更新操作
            studentService.update(student);
            //5.回写ok
            response.getWriter().write("ok");
        }catch (Exception e){
            response.getWriter().write("error");
        }
    }

    /**
     * 删除
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            //1.获取要删除的id
            String id = request.getParameter("id");
            //2.根据id删除学生信息
            studentService.delete(id);
            //3.回写ok
            response.getWriter().write("ok");
        }catch (Exception e){
            response.getWriter().write("error");
        }
    }
/**
 * 此方法是用于获取请求参数中method(action）属性的。
 * 根据属性的值，来执行不同的方法
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取action的值
String action = request.getParameter("action");
//2.判断是什么操作
if("findAll".equals(action)){
findAll(request,response);
}else if("save".equals(action)){
save(request,response);
}else if("findById".equals(action)){
findById(request,response);
}else if("update".equals(action)){
update(request,response);
}else if("delete".equals(action)){
delete(request,response);
}else if("findPage".equals(action)){
findPage(request,response);
}
}
 */
}